<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="姓名" size="small">
            <el-input v-model="searchForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="证件类型" size="small">
            <el-select v-model="searchForm.documentType" placeholder="请选择">
              <el-option value="" label="全部"></el-option>
              <el-option
                v-for="item in global.documentTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>

      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
      @openVisible="openVisible"
    >
      <el-table-column
        slot="opt"
        fixed="right"
        label="操作"
        width="120">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.documentId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="440px">
      <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
        <el-form-item prop="teamName" label="所属团队" size="small" class="item-inline">
          <el-autocomplete
            v-model="teamRow.teamName"
            :fetch-suggestions="querySearchTeam"
            @select="handleSelectTeam"
            placeholder="请输入内容"
          >
          </el-autocomplete>
        </el-form-item>
        <el-form-item prop="name" label="姓名" size="small">
          <el-input type="text" v-model="teamRow.name"></el-input>
        </el-form-item>
        <el-form-item prop="documentType" label="证件类型" size="small">
          <el-select v-model="teamRow.documentType" placeholder="请选择">
            <el-option
              v-for="item in global.documentTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="documentCode" label="证件编码" size="small">
          <el-input type="text" v-model="teamRow.documentCode"></el-input>
        </el-form-item>
        <el-form-item prop="maturityTime" label="证件到期时间" size="small" class="item-inline">
          <el-date-picker
            v-model="teamRow.maturityTime"
            type="date"
            value-format="timestamp"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="证件照片" size="small">
          <input type="file" ref='file' accept="image/*" @change="getFile($event)">
        </el-form-item>
        <el-form-item label="备注说明" size="small">
          <el-input type="textarea" v-model="teamRow.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
        <el-button size="small" @click="outerVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="imgMsg.label" :visible.sync="imgVisible" width="600px">
      <img class="img-dialog" :src="imgMsg.src" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import {
    addDocumentManagement,
    deleteDocumentManagement,
    getDocumentManagement,
    selectDocumentManagement,
    updateDocumentManagement,
    selectTeam
  } from '@/api/certificate'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const documentType = function(row, column) {
    if (row.documentType) {
      let obj = {}
      obj = global.documentTypeList.find((item) => {
        return item.value === row.documentType // 筛选出匹配数据
      })
      return obj.label
    }
  }

  const maturityTime = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const documentPhoto = {
    props: ['colConfig'],
    methods: {
      openVisible(label, src) {
        const msg = {
          label: label,
          src: src
        }
        this.$emit('openImgVisible', msg)
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        <div v-if="colConfig.type==='img'">
          <a v-if="scope.row[colConfig.prop]" @click="openVisible(colConfig.label,scope.row[colConfig.prop])">查看
          </a>
        </div>
        <div v-else>
          <a v-if="scope.row[colConfig.prop]" target="_blank" :href="GLOBAL.filePathUrl+ encodeURI(scope.row[colConfig.prop])">下载</a>
        </div>
      </span>
  </el-table-column>
  `
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [
          { prop: 'teamName', label: '团队名称', width: '150', fixed: true },
          { prop: 'name', label: '姓名', width: '150' },
          { prop: 'documentType', label: '类型证件', width: '150', formatter: documentType },
          { prop: 'documentCode', label: '证件编码', width: '150' },
          { prop: 'maturityTime', label: '证件到期时间', width: '150', component: maturityTime },
          { prop: 'documentPhoto', label: '证件照片', type: 'img', width: '150', component: documentPhoto },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        tenderNames: [],
        infoTitles: [],
        listLoading: true,
        dialogTitle: '新增证件管理',
        dialogType: 0,
        teamRow: {},
        teamRowClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        innerVisible: false,
        pca: pca,
        rules: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'change' }
          ],
          teamName: [
            { required: true, message: '请选择团队名称', trigger: 'change' }
          ],
          documentType: [
            { required: true, message: '请选择证件类型', trigger: 'change' }
          ],
          documentCode: [
            { required: true, message: '请输入证件编码', trigger: 'change' }
          ],
          maturityTime: [
            { required: true, message: '请选择证件到期时间', trigger: 'change' }
          ]
        },
        visible: false,
        imgVisible: false,
        imgMsg: {}
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    computed: {
      global() {
        return global
      },
      teamId() {
        return this.$store.state.user.teamId
      },
      isDirector() {
        return this.$store.state.user.isDirector
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.searchFormList.isDirector = this.isDirector
        this.searchFormList.teamId = this.teamId
        this.listLoading = true
        console.log(this.searchFormList)
        getDocumentManagement(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '新增证件管理'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.teamRow.isTender = 1
        this.dialogType = 1
        if (this.$refs.file) {
          this.$refs.file.value = ''
        }
        if (this.$refs.registration) {
          this.$refs.registration.value = ''
        }
        if (this.$refs.other) {
          this.$refs.other.value = ''
        }
      },
      editTeam(documentId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '修改证件管理'
        this.dialogType = 0
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        if (this.$refs.file) {
          this.$refs.file.value = ''
        }
        if (this.$refs.registration) {
          this.$refs.registration.value = ''
        }
        if (this.$refs.other) {
          this.$refs.other.value = ''
        }
        const params = {
          documentId: documentId
        }
        selectDocumentManagement(params).then(response => {
          const data = response.responseBody
          this.teamRow = Object.assign({}, this.teamRow, data)
        })
      },
      submitForm(formName) {
        const params = new FormData()
        params.append('name', this.teamRow.name)
        params.append('teamId', this.teamRow.teamId)
        params.append('teamName', this.teamRow.teamName)
        params.append('file', this.teamRow.file)
        params.append('documentType', this.teamRow.documentType)
        params.append('maturityTime', this.teamRow.maturityTime)
        params.append('documentCode', this.teamRow.documentCode ? this.teamRow.documentCode : '')
        params.append('remark', this.teamRow.remark ? this.teamRow.remark : '')
        if (!this.dialogType) {
          params.append('documentId', this.teamRow.documentId)
        }
        if (this.teamRow.teamId) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.dialogType) {
                addDocumentManagement(params).then(response => {
                  console.log(response)
                  this.outerVisible = false
                  this.fetchData()
                })
              } else {
                updateDocumentManagement(params).then(response => {
                  console.log(response)
                  this.outerVisible = false
                  this.fetchData()
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        } else {
          this.$message({
            message: '该团队不存在',
            type: 'warning'
          })
        }
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = new FormData()
        params.append('documentId', scope.row.documentId)
        params.append('isDel', 1)
        deleteDocumentManagement(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      getFile(event) {
        this.teamRow.file = event.target.files[0]
      },
      getRegistration(event) {
        this.teamRow.registration = event.target.files[0]
      },
      getOther(event) {
        this.teamRow.other = event.target.files[0]
      },
      querySearchTeam(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.teamId
        if (queryString) {
          const params = {
            teamName: queryString
          }
          selectTeam(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.teamName
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      handleSelectTeam(item) {
        console.log(item)
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
      },
      openVisible(msg) {
        this.imgVisible = true
        this.imgMsg = msg
      }
    },
    mounted() {
      console.log(this.pca)
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
    .img-dialog {
      max-width: 540px;
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  a, a:focus, a:hover {
    color: #409EFF;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
